use std::collections::HashMap;
use sdl2::controller::Button;
use sdl2::event::Event;
use sdl2::controller::GameController;
use sdl2::EventPump;
fn main() {
    // println!("Hello, world!");
    let sdl_context = sdl2::init().unwrap();
    // let video_subsystem = sdl_context.video().unwrap();
    // let _window = video_subsystem
    //     .window("手柄测试", 640, 480)
    //     .position_centered()
    //     .vulkan()
    //     .build()
    //     .unwrap();


    let controller_subsystem = sdl_context.game_controller().unwrap();
    // 事件队列
    let mut event_pump = sdl_context.event_pump().unwrap();
    // 必须持有手柄对象才可以获取事件
    let mut controllers: HashMap<u32, GameController> = HashMap::new();
    let mut count = 0;
    loop {
        for event in event_pump.poll_iter() {
            match event {
                Event::ControllerDeviceAdded { timestamp, which } => {
                    let controller = controller_subsystem.open(which).unwrap();
                    println!("手柄连接: {}", controller.instance_id());
                    println!("手柄名称: {}", controller.name());
                    controllers.insert(controller.instance_id(), controller);
                }
                Event::ControllerDeviceRemoved { timestamp, which } => {
                    println!("手柄断开: {}", which);
                    controllers.remove(&which);
                }
                Event::ControllerAxisMotion { timestamp, which, axis, value } => {
                    println!("手柄轴运动: {} {:?} {}", which, axis, value);
                }
                Event::ControllerButtonDown { timestamp, which, button } => {
                    println!("手柄按钮按下: {} {:?}", which, button);
                    if button == Button::A {
                        let controller = controllers.get_mut(&which).unwrap();
                        // 主震动
                        controller.set_rumble(0x3000, 0x3000, 1000).unwrap();
                    }
                    if button == Button::B {
                        let controller = controllers.get_mut(&which).unwrap();
                        // 扳机震动
                        if controller.has_rumble_triggers() {
                            controller.set_rumble_triggers(0x3000, 0x3000, 1000).unwrap();
                        }
                    }

                    
                }
                Event::ControllerButtonUp { timestamp, which, button } => {
                    println!("手柄按钮释放: {} {:?}", which, button);
                }
                _ => {}
            }
        }
    }
    
}
